<template>
  <div id="userLogin">
    <h2>用户登录</h2>
    <a-form
      :model="form"
      @submit="handleSubmit"
      label-align="left"
      auto-label-width
      style="max-width: 480px; margin: auto"
    >
      <a-form-item
        field="userAccount"
        tooltip="Please enter username"
        label="账号"
      >
        <a-input v-model="form.userAccount" placeholder="请输入账号" />
      </a-form-item>
      <a-form-item field="userPassword" label="密码">
        <a-input v-model="form.userPassword" placeholder="请输入密码" />
      </a-form-item>
      <a-form-item>
        <a-button html-type="submit">登录</a-button>
      </a-form-item>
    </a-form>
  </div>
</template>
<script setup lang="ts">
import { reactive } from "vue";
import { UserControllerService } from "../../../generate";
import store from "@/store";
import message from "@arco-design/web-vue/es/message";
import { useRoute, useRouter } from "vue-router";

const route = useRoute();
const router = useRouter();

const form = reactive({
  userAccount: "",
  userPassword: "",
});
const handleSubmit = async (data: any) => {
  if (!form.userAccount || !form.userPassword) {
    message.error("用户名和密码不能为空");
    return;
  }
  try {
    const res = await UserControllerService.userLoginUsingPost(form);
    if (res.code === 0) {
      await store.dispatch("user/getLoginUser");
      const redirect = route.query.redirect as string;
      await router.push({ path: redirect || "/", replace: true });
    } else {
      message.error("查询失败：" + res.message);
    }
  } catch (error) {
    message.error("网络错误，请稍后再试");
  }
};
</script>
